<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

</head>

<body>
<div>
    <video id="localVideo" width="640" height="480" autoplay></video>
    <video id="miniVideo" width="640" height="480" autoplay></video>
    <video id="remoteVideo" width="640" height="480" autoplay></video>
</div>
<div algin="center">
    <input type ="button" value="开始" onclick="con()"/>
    <input type ="button" value="发送" onclick="send()"/>
</div>
</body>
</html>
<script>
    var socket =new WebSocket('ws://'+window.location.host + '/forum-web/websocket.ws');
    window.onload = initialize();
    function initialize() {
        <%--console.log("Initializing; room=${roomKey}.");--%>
        card = document.getElementById("card");
        localVideo = document.getElementById("localVideo");
        miniVideo = document.getElementById("miniVideo");
        remoteVideo = document.getElementById("remoteVideo");
//        resetStatus();
        openChannel();
        getUserMedia();
    }
    function openChannel() {
        console.log("Opening channel.");
//        socket.onopen = onChannelOpened;
        socket.onmessage = onChannelMessage;
//        socket.onclose = onChannelClosed;
        socket.onopen = function(evt){
            console.log("open");
        };
        socket.onclose=function(evt){
            console.log(evt);
        };
    }

    function getUserMedia() {
        try {
//            navigator.getUserMedia({
//                'audio' : true,
//                'video' : true
//            }, onUserMediaSuccess, onUserMediaError);
            navigator.getUserMedia=(navigator.getUserMedia ||
            navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia ||
            navigator.msGetUserMedia);
            navigator.getUserMedia({
                'audio' : true,
                'video' : true
            },onUserMediaSuccess,function error(error){console.log(error);});

            console.log("Requested access to local media with new syntax.");
        } catch (e) {
            try {
                navigator.webkitGetUserMedia("video,audio",
                    onUserMediaSuccess, onUserMediaError);
                console
                    .log("Requested access to local media with old syntax.");
            } catch (e) {
                alert("webkitGetUserMedia() failed. Is the MediaStream flag enabled in about:flags?");
                console.log("webkitGetUserMedia failed with exception: "
                    + e.message);
            }
        }
    }

    function onUserMediaSuccess(stream) {
        console.log("User has granted access to local media.");
        var url = window.URL.createObjectURL(stream);
        localVideo.style.opacity = 1;
        localVideo.src = url;
        localStream = stream;
        // Caller creates PeerConnection.

        maybeStart();
    }

    function maybeStart() {
        pc = new RTCPeerConnection({
            iceServers: [     // Information about ICE servers - Use your own!
                {
                    urls: "turn:" + window.location.host,  // A TURN server
                    username: "webrtc",
                    credential: "turnserver"
                }
            ]
        });
//            setStatus("Connecting...");
            console.log("Creating PeerConnection.");
//            createPeerConnection();
            console.log("Adding local stream.");
            pc.addStream(localStream);
            started = true;
//            // Caller initiates offer to peer.
//            if (initiator)
//                doCall();

    }

    function doCall() {
        console.log("Sending offer to peer.");
        if (isRTCPeerConnection) {
            pc.createOffer(setLocalAndSendMessage, null, mediaConstraints);
        } else {
            var offer = pc.createOffer(mediaConstraints);
            pc.setLocalDescription(pc.SDP_OFFER, offer);
            sendMessage({
                type : 'offer',
                sdp : offer.toSdp()
            });
            pc.startIce();
        }
    }

    function setLocalAndSendMessage(sessionDescription) {
        pc.setLocalDescription(sessionDescription);
        sendMessage(sessionDescription);
    }

    function sendMessage(message) {
        var msgString = JSON.stringify(message);
        console.log('发出信息 : ' + msgString);
        path = 'message?r=${roomKey}' + '&u=${user}';
        var xhr = new XMLHttpRequest();
        xhr.open('POST', path, true);
        socket.send(msgString);
    }
    function onChannelMessage(message) {
        console.log('收到信息 : ' + message.data);

            processSignalingMessage(message.data);//建立视频连接

    }

    function processSignalingMessage(message) {
        var msg = JSON.parse(message);

        if (msg.type === 'offer') {
            // Callee creates PeerConnection
            if (!initiator && !started)
                maybeStart();

            // We only know JSEP version after createPeerConnection().
            if (isRTCPeerConnection)
                pc.setRemoteDescription(new RTCSessionDescription(msg));
            else
                pc.setRemoteDescription(pc.SDP_OFFER,
                    new SessionDescription(msg.sdp));

            doAnswer();
        } else if (msg.type === 'answer' && started) {
            pc.setRemoteDescription(new RTCSessionDescription(msg));
        } else if (msg.type === 'candidate' && started) {
            var candidate = new RTCIceCandidate({
                sdpMLineIndex : msg.label,
                candidate : msg.candidate
            });
            pc.addIceCandidate(candidate);
        } else if (msg.type === 'bye' && started) {
            onRemoteHangup();
        }
    }
</script>
